<template>
  <div>
    <explanation :explanation="explanationObj" class="explanation-component"/>
    <div :class="{'mobile-create': showMobilePage}" class="pay-application-container">
      <PayApplicationForm
        ref="WithDrawForm"
        :settle-id="settleId"
        :step-three-data="stepThreeData"
        :step-one-data="stepOneData"
        :total-price="stepThreeData.totalPrice"
        :is-edit="isEdit"
        :is-not-order="isNotOrder"
        :is-launch-examine="isLaunchExamine"
        :show-draft="showDraft"
        @setIsSaveCollectMoneyData="setIsSaveCollectMoneyData"
        @openHistoryDrawer="openHistoryDrawer"
        @changeProposer="changeProposer"
      />
      <AuditProcess
        ref="auditProcess"
        :loading="processLoading"
        v-model="aduitInfo"
        :default-aduitor-list="[proposer]"
        :is-signer="isSigner"
        :old-audit-info="oldAuditInfo"
        :flow-structure="processDetail"
        :is-modify="Boolean(isEdit) && !stepThreeData.isDraft"
        :disable="Boolean(isEdit) && !stepThreeData.isDraft"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        :submit-loading="loading"
        @submit="submitExamine(false,$event)"
        @getProcess="getProcess" />
      <selectHistoryFormData
        ref="selectHistoryFormData"
        :visible.sync="showSelectHistoryFormData"
        @confirmSelectData="confirmSelectData"
      />
    </div>
    <fixed-pagination>
      <div class="center">
        <el-checkbox v-model="isSaveCollectMoneyData" style="margin-right:10px;margin-top:6px;">保存收款账户</el-checkbox>
        <template v-if="!showMobilePage">
          <el-button v-if="showLastStepBtn" :loading="loading" type="primary" size="small" class="pre-step plain-create-btn" @click="backStep">上一步</el-button>
          <el-button :loading="loading" :disabled="processLoading" type="primary" size="small" @click="openDrawer">发起审批</el-button>
          <el-button v-if="showDraft" :loading="loading" type="primary" class="plain-create-btn" size="small" @click="submitExamine(true)">保存草稿</el-button>
          <el-button v-if="isAccountSettle" size="small" type="info" class="back-btn cancel-btn-style" @click="toBack">返回</el-button>
          <el-button v-if="isEdit || isLaunchExamine" :loading="loading" type="info" class="back-btn cancel-btn-style" size="small" @click="toCancel">取消</el-button>
          <back-btn text="返回列表" to-list />
        </template>

        <template v-else>
          <el-button :loading="loading" :disabled="processLoading" type="primary" size="small" @click="openDrawer">发起审批</el-button>
          <MoreOpeator
            :list="[
              {label: '保存草稿', handelClick: ()=>submitExamine(true), auth: showDraft},
              {label: '上一步', handelClick: backStep, auth: showLastStepBtn},
              {label: '返回', handelClick: toBack, auth: isAccountSettle},
              {label: '取消', handelClick: toCancel, auth: isEdit || isLaunchExamine},
            ]"
            label="更多"
            style="margin-left: 12px"
          />
        </template>

      </div>
    </fixed-pagination>
  </div>
</template>
<script>
/**
 * 付款申请第三步骤：付款申请
 */

// components
import explanation from '@/components/Common/explanation';
import PayApplicationForm from '../components/payApplicationForm';
import Title from '@/components/Title';
import AuditProcess from '@/components/Common/auditProcess';
import selectHistoryFormData from '@/components/CreateOrder/selectHistoryFormData';
import processCreate from '@/mixins/processCreate';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import BackBtn from '@/components/SupplierComponent/module/backBtn';
// utils
import { mapState } from 'vuex';
import { ROLE_TYPE } from '@/utils/const/process';
import { SUBMITTYPE } from '@/utils/const/cost';
import { showModal } from '@/utils/message';
import ElMessage from '@/utils/message';
import { isContained } from '@/utils/tools';
import { createAuditStructure } from '@/utils/aduitor';
import { encryption } from '@/utils';
// import math from '@/utils/math';
// api
import { currentWidthdrawInfo, examineRevoke, formSubmit, launchExamine } from '@/api/supplier';
import { processManagementDetail } from '@/api/legal';

export default {
  components: { explanation, Title, PayApplicationForm, AuditProcess, selectHistoryFormData, MoreOpeator, BackBtn },
  mixins: [processCreate],
  model: {
    prop: 'stepThreeData',
    event: 'changeValue'
  },
  props: {
    stepThreeData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    stepTwoData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    stepOneData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    settleId: {
      type: String | Number,
      default: ''
    },
    isNotOrder: { // 非订单请款
      type: Boolean,
      default: false
    },
    isEdit: { // 修改审批单，审批流程不能修改
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      SUBMITTYPE,
      isSaveCollectMoneyData: false,
      loading: false,
      showSelectHistoryFormData: false,
      proposerData: null,

      // 流程相关数据
      processDetail: null,
      reapplyId: null, // 重新申请
      explanationObj: { // 审批说明
        content: '',
        styConfig: ''
      }, // 审批说明
      processLoading: false,
      aduitInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      }, // 流程信息
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动,
      isModifyForm: 0, // 审批中时在某个节点进行修改
      currentProcessIndex: -1,
      // 1:发起审批，不会填内容 2:申请余款，回填内容
      isLaunchExamine: 0, // 发起审批入口。在同一个结算单上发起一个新的审批单
      createNew: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isInvite() {
      return !!this.stepOneData.isInvite;
    },
    isAccountSettle() { // 是否待办详情账号结算
      return !!this.$route.query.isAccountSettle;
    },
    showLastStepBtn() {
      // 获取审批单列表中是否存在已完成
      const isExamined = !!this.$route.query.isExamined;
      return !this.isAccountSettle &&
      !this.isNotOrder && !this.isLaunchExamine && !this.isModifyForm &&
      (!this.isEdit ||
        (this.isEdit && !this.stepThreeData.isDraft) // 编辑非草稿
      ) && !isExamined;
    },
    showDraft() {
      return (!this.isEdit || this.stepThreeData.isDraft) && !this.isLaunchExamine;
    },
    proposer() {
      const proposerData = this.proposerData;
      if (proposerData) {
        return { ...proposerData };
      }
      const { id, userName, avatar, jobNumber, post } = this.userInfo;
      return {
        id,
        userName,
        avatar,
        number: jobNumber,
        post
      };
    },
    isSigner() {
      // 【v2.8.6】加签人设置 （countersignSet 1: 添加加签人不限制， 2:申请人不允许加签，3: 审批人不允许加签 ）
      const countersignSet = this.aduitInfo.countersignSet;
      if (countersignSet === 2) { // 这里的申请人 包括 创建人 和 申请人
        return false;
      }
      return true;
    }
  },
  created() {
    this.createNew = Number(this.$route.query.createNew) || 0;
    const examineId = Number(this.$route.query.examineId) || 0; // 审批单id

    // 在同一个结算单上发起一个新的审批单 isLaunchExamine 1:发起审批，不会填内容 2:申请余款，回填内容
    this.isLaunchExamine = Number(this.$route.query.isLaunchExamine || 0);
    this.isModifyForm = Number(this.$route.query.isModifyForm) || 0;
    // currentProcessIndex 用于审批中修改时，通知当前节点之前的人员
    const currentProcessIndex = this.$route.query.currentProcessIndex;
    if (currentProcessIndex || currentProcessIndex === 0) {
      this.currentProcessIndex = Number(currentProcessIndex);
    }
    if (examineId) {
      // 编辑
      this.getCurrentWidthdrawInfo(examineId);
    }
    this.reapplyId = this.$route.query.reapplyId || null;
    this.getExplanation();
  },
  methods: {
    createAuditStructure,
    /**
     * 发起审批
     */
    openDrawer() { // 2.9.7 流程弹窗
      const paramsData = this.$refs.WithDrawForm.getParams();
      let validate = [];
      const withDrawFormRef = this.$refs.WithDrawForm.geValidate();
      // 保存草稿不做验证
      validate = withDrawFormRef;
      // 发票列表中不能存在重复的发票代码和发票号码
      // 对公银行/其他账户 且 已取得发票,
      if ([2, 3].includes(paramsData.accountType) && paramsData.invoice === 0 &&
        paramsData.invoiceList && paramsData.invoiceList.length) {
        const allInvoiceNumber = [];
        for (let i = 0; i < paramsData.invoiceList.length; i++) {
          const item = paramsData.invoiceList[i];
          const repeatInvoiceNumber = item.invoiceNumber && allInvoiceNumber.includes(item.invoiceNumber);
          if (repeatInvoiceNumber) {
            ElMessage.error(`发票列表中存在重复的发票号码`);
            return;
          }
          if (item.invoiceNumber) allInvoiceNumber.push(item.invoiceNumber);
        }
      } else if ([2, 3].includes(paramsData.accountType) && (!paramsData.invoiceList || !paramsData.invoiceList.length) && paramsData.invoice === 0) {
        ElMessage.error(`请添加发票信息`);
        return;
      }
      const relatedContractVal = this.$refs.WithDrawForm.validateRelateContract();
      if (relatedContractVal) {
        ElMessage.error('请添加关联合同！');
        return;
      }
      if (this.isInvite) {
        let length = 0;
        this.stepThreeData.selectCost && this.stepThreeData.selectCost.map(it => {
          if (it.costList && it.costList.length) {
            length += it.costList.length;
          }
          if (it.orderList && it.orderList.length) {
            length += it.orderList.length;
          }
        });
        if (!length) {
          ElMessage.error('请添加订单！');
          return;
        }
      }

      Promise.all(validate.map(this.getFormPromise)).then(async res => {
        /**
         * 规则：
         * 多次结算：本次结算总金额必须小于等于订单未结算金额
         * 一次结算：结算总金额必须等于订单结算总金额
         * 一下金额的单位都是分
         * 以上逻辑改为接口判断
         */
        this.getProcessDetail();
      }).catch(err => {
        const errMsg = err && typeof err === 'string' ? err : '请检查信息是否填写完整';
        ElMessage.error(errMsg);
      });
    },
    // 发起审批，isDraft：是否保存草稿
    submitExamine(isDraft = false, senders = [], isInvite = false) {
      let validate = [];
      const withDrawFormRef = this.$refs.WithDrawForm.geValidate();
      // 保存草稿不做验证
      if (!isDraft) {
        validate = withDrawFormRef;
      }
      // 订单请款或者账号结算存在达人结算节点检验是否为空，为空则未关联飞来用户
      if (!this.hasLinkFlyUser() && !this.isNotOrder && !isDraft) {
        return;
      }
      Promise.all(validate.map(this.getFormPromise)).then(async res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
          const paramsData = this.$refs.WithDrawForm.getParams();
          this.version = Number(paramsData.version) || 0;// 当前详情版本，version存在mixins
          paramsData.isDraft = 0;
          if (isDraft) paramsData.isDraft = 1; // 保存草稿
          if (this.settleId) paramsData.id = this.settleId;
          paramsData.isInvite = this.isInvite;
          paramsData.aduitInfo = this.aduitInfo;
          paramsData.isEditAudit = false;
          paramsData.settlementMethod = this.stepOneData.settlementMethod;
          if (Boolean(this.isEdit) && this.isRefresh) {
            paramsData.isEditAudit = true;// 修改时，流程被编辑或者更新
          }
          if (this.isLaunchExamine === 2) { // 点击申请余额进来时，要删除workFlowId
            delete paramsData.workFlowId;
          }
          paramsData.isNotOrder = this.isNotOrder;
          paramsData.isSaveCollectMoneyData = this.isSaveCollectMoneyData;

          if (paramsData.contractList && paramsData.contractList.length) {
            paramsData.contractList.forEach(it => {
              if (typeof it.proposerName === 'number') {
                it.proposer = it.proposerName;
                delete it.proposerName;
              }
            });
          }
          if (this.isEdit && this.isModifyForm) { // 节点修改
            paramsData.invoiceList = paramsData.invoiceList.concat(this.$refs.WithDrawForm.delInvoiceList || []);
            this.handleModifyData(paramsData, senders);
            this.launchExamine(paramsData);
            return;
          }
          if (this.isEdit) { // 从审批记录列表点击修改进入时,需要提交被删除的发票列表
            this.handleModifyData(paramsData);
            paramsData.invoiceList = paramsData.invoiceList.concat(this.$refs.WithDrawForm.delInvoiceList || []);
          }
          const msg = isDraft ? '请确认是否保存草稿' : '请确认是否发起审批';
          if (isInvite) {
            this.launchExamine(paramsData, isInvite);
          } else {
            showModal(msg, '', {
              confirmButtonText: '确定', type: 'warning', showClose: false,
              center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
            }).then(() => {
              this.launchExamine(paramsData);
            });
          }
        } else {
          return false;
        }
      }).catch(err => {
        const errMsg = err && typeof err === 'string' ? err : '请检查信息是否填写完整';
        ElMessage.error(errMsg);
      });
    },

    launchExamine(paramsData, isInvite = false) {
      this.loading = true;
      if (paramsData.accountType === 1) {
        delete paramsData.invoice;
      }
      // 订单选择时没有创建草稿，需要传额外参数
      if (this.stepTwoData && this.stepTwoData.id) {
        paramsData.orderSelect = this.stepTwoData;
      }
      launchExamine(paramsData).then(result => {
        if (!isInvite) {
          this.$message.success('操作成功');

          // isReApplyAfterCall 发起后继续申请
          if (this.$refs.auditProcess.isReApplyAfterCall) {
            this.$emit('reApplyAfterCall');
            this.$refs.auditProcess.isReApplyAfterCall = false;
            this.isSaveCollectMoneyData = false;
            this.$refs.selectHistoryFormData.init();
            this.$refs['auditProcess'].handleClose();
          } else {
            const query = {
              settleId: this.settleId || result.data.settleId, // 结算id
              id: this.stepOneData.supplierId || paramsData.channelId, // 供应商id
              isSettle: true
            };
            if (this.isInvite) {
              query.isInvite = encryption(this.settleId);
            }
            this.$router.push({
              name: 'supplierDetail',
              query
            });
          }
        }
        this.loading = false;
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'supplierDetail', params: {}, query: { settleId: this.settleId, id: this.stepOneData.supplierId, isSettle: true }});
        }
        if (err.code === 504) { // 个合作运营方同时发起审批
          showModal('暂不支持多个合作运营方同时发起审批，请确保请款账号的合作运营方是相同的', '', {
            confirmButtonText: '确定',
            showCancelButton: false,
            customClass: 'del-message del-message-cancel withdraw-message'
          }).then(_ => {
          });
        }
        if (err.code === 506) { // 未关联飞来用户 || 非订单情况含有飞来通告节点
          showModal(err.message, '', {
            confirmButtonText: '确定',
            showCancelButton: false,
            customClass: 'del-message del-message-cancel withdraw-message'
          }).then(_ => {
            this.getProcess();
          });
        }
        this.loading = false;
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      const tempData = this.$refs.WithDrawForm._data;
      // 对公银行/其他账户 且 已取得发票,
      if ([2, 3].includes(tempData.headForm.accountType) && tempData.headForm.invoice === 0 && this.invoiceValidate()) {
        return;
      }
      this.processLoading = true;
      const data = Object.assign({}, JSON.parse(JSON.stringify(this.$refs.WithDrawForm.getParams())));
      data.isDraft = data.isDraft ? 1 : 0;
      data.type = 3;
      if (this.settleId) {
        data.id = this.settleId;
      }
      if (data.accountType === 1) {
        delete data.invoice;
      }
      data.isNotOrder = this.isNotOrder;
      data.isInvite = this.isInvite;
      if (this.isEdit) { // 节点修改
        data.invoiceList = data.invoiceList.concat(this.$refs.WithDrawForm.delInvoiceList || []);
      }
      if (this.stepTwoData && this.stepTwoData.id) {
        data.orderSelect = this.stepTwoData;
      }
      return new Promise((resolve, reject) => {
        formSubmit(data).then(res => {
          this.processLoading = false;
          if (res.code === 200) {
            const resData = res.data;
            if (this.isEdit && !this.stepThreeData.isDraft && !isRefresh) {
              this.isProcessChange(resData, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
            } else {
              this.processDetail = Object.assign({}, resData);
              this.aduitInfo = Object.assign({}, resData);
              this.aduitInfo.senders = this.aduitInfo.senders && this.aduitInfo.senders.length ? this.aduitInfo.senders || [] : this.aduitInfo.senderDiyUserList || [];
              // 创建人和申请人自动回填 start
              this.aduitInfo.process = this.createAuditStructure(this.aduitInfo.process, this.userInfo, this.proposer);
              // 创建人和申请人自动回填 end
              this.$set(this.aduitInfo, 'isSigner', this.aduitInfo.isSigner || 0);
              this.$set(this.aduitInfo, 'countersignSet', this.aduitInfo.countersignSet || 0);
              this.aduitInfo.activeTime = resData.activationTime;
              this.aduitInfo.id = resData.id;
              resolve(resData);
            }
            if (this.isEdit && isRefresh) { // 修改刷新保存刷新后流程用于对比
              this.oldAuditInfo = Object.assign({}, resData);
              this.oldAuditInfo.process.forEach(el => {
                this.oldAuditInfo.templateNodeId = el.id;
              });
              this.oldAuditInfo.activeTime = resData.activationTime * 1000;
            }
            this.$refs['auditProcess'].openDrawer();
          } else {
            this.$message.error(res.message);
          }
        }).catch(err => {
          this.processLoading = false;
          reject(err);
        });
      });
    },
    /**
     * 获取数据
     */
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 4, type: 3 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },

    // 获取当前审批单数据 并 回填
    getCurrentWidthdrawInfo(examineId) {
      // examineId 审批单id--需修改由下面的审批单提供
      currentWidthdrawInfo(examineId).then(res => {
        if (res.data) {
          this.handleDetailData(res);
          if (this.isEdit && res.data.aduitInfo) {
            this.aduitInfo = JSON.parse(JSON.stringify(res.data.aduitInfo));
            this.processDetail = JSON.parse(JSON.stringify(Object.assign({}, res.data.aduitInfo)));
          }
          // isLaunchExamine 1:发起审批，不会填内容 2:申请余款，回填内容
          if (this.isLaunchExamine === 2 || this.isEdit || this.createNew) {
            this.$refs.WithDrawForm.insertData(res.data);
          } else {
            this.$refs.WithDrawForm.setSettleName(res.data.settleName);
            // 其他付款结算(非订单)回填结算总金额
            if (this.isNotOrder) this.$refs.WithDrawForm.insertSettleMount(res.data);
          }
          // if (this.isNotOrder) {
          this.$refs.WithDrawForm.setSupplier(res.data);
          if (this.createNew && this.isNotOrder) { // 复制结算单回填结算方式
            const { settlementMethod } = res.data;
            this.stepOneData.settlementMethod = typeof settlementMethod === 'number' ? settlementMethod : null;
          }
          // }
        }
      }).catch(err => {
        console.error(err);
      });
    },
    handleDetailData(res) { // 处理详情数据
      if (!res.data.collectAccount) {
        res.data.collectAccount = {
          bank: '', payName: '', payNum: '', province: '', subBank: ''
        };
      } else {
        if (res.data.collectAccount.province) {
          res.data.collectAccount.province = res.data.collectAccount.province.replace(/-/g, ',');
        }
      }
      if (res.data.collectMoneyData && res.data.collectMoneyData.list) {
        res.data.collectMoneyData.list.map(item => {
          item.settlementAmount = item.settlementAmount || item.settlementAmount === 0 ? (item.settlementAmount / 100).toFixed(2) : item.settlementAmount;
          item.withdrawAmount = item.withdrawAmount || item.withdrawAmount === 0 ? (item.withdrawAmount / 100).toFixed(2) : item.withdrawAmount;
          item.actualAmount = item.actualAmount || item.actualAmount === 0 ? (item.actualAmount / 100).toFixed(2) : item.actualAmount;
          return item;
        });
      }
      if (res.data.contractList === null) res.data.contractList = [];
      if (res.data.contractSign === 0 && res.data.contractList && res.data.contractList.length) {
        res.data.contractList.forEach(it => {
          it.userName = it.proposerName;
          if (it.contractSourceType === 1) it.disable = true;
        });
      }
      // 发起新审批和申请余款时要把发票列表的id清掉
      if (this.isLaunchExamine || this.createNew) {
        res.data.invoiceList.forEach(item => {
          delete item.id;
        });
      }
      if (this.createNew && res.data.accountType !== 1 && res.data.invoiceList.length > 0) {
        res.data.invoice = 0;
      }
      // 非订单请款手填结算总金额
      if (!this.createNew) {
        res.data.settleAmountTotal = this.stepThreeData.settleAmountTotal;
      }
      if (res.data.settlementAmountTotal) res.data.settlementAmountTotal = Math.round(res.data.settlementAmountTotal * 100) / 100;
    },
    /**
     * change 事件
     */

    // 节点修改，流程变更跳转详情页
    nodeModifyJumpDetail({ routeName = '', params = {}, query = {}}) {
      query.routeKey = new Date().getTime();
      this.$router.push({
        name: routeName,
        params,
        query
      });
    },
    invoiceValidate() {
      let result = false;
      const invoiceList = this.$refs.WithDrawForm.headForm.invoiceList;
      if (!invoiceList.length) {
        ElMessage.warning('发票信息不能为空！');
        result = true;
      } else {
        if (invoiceList[0].invoiceNumber) {
          // 验证发票号码唯一性
          const temp = invoiceList.map(item => item.invoiceNumber);
          if (Array.from(new Set(temp)).length < temp.length) {
            ElMessage.warning('发票号码重复！');
            result = true;
          }
        }
        // 校验发票号码是否为0
        invoiceList.map(it => {
          if (Number(it.invoicePrice) === 0) {
            ElMessage.warning('含税金额不能为零！');
            result = true;
          }
          // 含税金额税额同正同负校验
          if (it.invoicePrice * it.tax < 0) {
            ElMessage.warning('含税金额与税额存在错误，应同正同负！');
            result = true;
          }
        });
      }
      return result;
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    hasLinkFlyUser() {
      let hasLinkFlyUser = true;
      let accountName = '';
      if (this.processDetail && this.processDetail.process) {
        this.processDetail.process.forEach(j => {
          let roles = [];
          if (j.examineRoles && j.examineRoles.length) {
            roles = roles.concat(j.examineRoles);
          }
          const item = roles.find(i => i.roleType === 11);
          if (item) {
            hasLinkFlyUser = !!((item.diyUserList && item.diyUserList.length) || (this.isEdit && item.aduitors && item.aduitors.length));
          }
          if (j.nodeType === 4 && j.accountNames && j.accountNames.length) { // 达人结算节点
            accountName = j.accountNames.join(';');
          }
        });
      }

      if (!hasLinkFlyUser) {
        showModal('该账号所属供应商没有关联启用的飞来用户无法进行消息推送，请关联后再发起', '', {
          confirmButtonText: '前往关联',
          cancelButtonText: '取消'
        }).then(_ => {
          this.toFlyUser(accountName);
        });
      }
      return hasLinkFlyUser;
    },
    toFlyUser(accountName) {
      const routeUrl = this.$router.resolve({
        name: 'flyUser',
        query: {
          accountName
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    changeProposer() {
      if (!this.aduitInfo) return;
      const paramsData = this.$refs.WithDrawForm.getParams();
      const proposer = paramsData.proposerUserObj;
      this.proposerData = proposer;
      if (this.processDetail && this.processDetail.process) {
        for (var s = 0; s < this.processDetail.process.length; s++) {
          const process = this.processDetail.process[s];
          for (var r = 0; r < process.examineRoles.length; r++) {
            const examineRole = process.examineRoles[r];
            if (examineRole.roleType === ROLE_TYPE.PROPOSER) {
              this.aduitInfo.process[s].examineRoles[r].aduitors = [proposer];
            }
          }
        }
      }
      this.oldAuditInfo = Object.assign({}, this.aduitInfo);
    },
    setIsSaveCollectMoneyData(v) {
      this.isSaveCollectMoneyData = v || false;
    },
    /**
     * 引用历史表单
     */
    openHistoryDrawer() {
      this.showSelectHistoryFormData = true;
    },
    confirmSelectData(data) {
      this.showSelectHistoryFormData = false;
      this.$refs.WithDrawForm.fillHistory(data);
    },
    /**
     * 操作
     */
    getFormPromise(form) {
      return form.validate();
    },
    backStep() {
      this.$emit('changeValue', {});
      if (this.settleId && !this.isEdit) {
        const params = {
          currentStep: 1,
          lastStep: 0
        };
        examineRevoke(this.settleId, params).then(res => {
          this.$message.success('操作成功');
          this.$emit('setStepId', { process: 1 });
        }).catch(err => {
          console.error(err);
        });
      } else {
        this.$emit('setStepId', { process: 1 });
      }
    },
    toBack() {
      if (this.settleId) {
        examineRevoke(this.settleId).then(res => {
        }).catch(err => {
          console.error(err);
        });
      }
      this.$router.back();
    },
    toCancel() {
      this.loading = false;
      const newQuery = JSON.parse(JSON.stringify(this.$route.query));
      if (this.isInvite) {
        newQuery.isInvite = encryption(newQuery.settleId);
      }
      newQuery.isSettle = true;
      delete newQuery.isLaunchExamine;
      delete newQuery.examineId;
      delete newQuery.isDeleteInvoiceId;
      if (newQuery.isExamined) delete newQuery.isExamined;
      if (newQuery.isModifyForm) {
        delete newQuery.isModifyForm;
        delete newQuery.currentProcessIndex;
        delete newQuery.modifyNodeId;
      }
      this.$router.push({
        name: 'supplierDetail',
        query: newQuery
      });
    },
    changeValue(data) {
      this.$emit('changeValue', data);
    }
  }
};
</script>
<style lang="scss" scoped>
.explanation-component {
  margin-bottom: 0px !important;
}
.pay-application-container {
  padding: 0 24px;
  margin-top: 8px !important;
  .audit-process-content {
    width: 790px;
    opacity: 1;
    padding: 20px 32px 25px 16px;
  }

  & ::v-deep {
    .el-dialog__footer {
      text-align: center !important;
    }
    .legal-module-row {
      width: 50%;
    }
    .header-box {
      margin-top: 0;
    }
    .collet-container {
      margin-top: 32px;
    }
  }
  .dialog-footer {
    .pre-step {
      background-color: #fff;
      color: #406EFF;
    }
  }
  .plain-create-btn {
    background: #fff !important;
    color: #406EFF !important;
    border-color: #406EFF !important;
    &:hover {
      background-color: #406EFF !important;
      color: #fff !important;
    }
  }
}
.mobile-create {
  padding: 0 !important;
}
</style>
